const api = require("../../config/api");

// pages/MyList/MyList.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        AllList: [],
        MyList: [], // 保存工单上需要更新的信息
        electricianCode: '', // 电工编号 
        typeOptions: ['派遣', '发布', '所有'], // 可选类型数组
        selectedType: '所有',  // 默认选择显示的类型
        workOrderType: '', // 工单类型  
        mPageNum: 1,

        // 工单状态
        workOrderStateInfo: [],
        footer: {},
    },

    /**
   * 跳转工单列表
   */
  toWorkOrderList(e) {
    wx.navigateTo({
      url: "/pages/workOrderList/workOrderList?workOrderState=" + e.currentTarget.dataset.state
    });
  },

    // 获取每个状态的订单数量
    getOrderState(){
        // 本地获取电工编号
        wx.getStorage({
            key: 'electricianCode',
            success: (RES) => {
                this.setData({
                    electricianCode: RES.data.electricianCode
                })
                console.log('electricianCode', this.data.electricianCode)
                // 获取成功，请求接口
                wx.request({
                  url: api.getWorkOrderStatisticsToElectrician,
                  method:'POST',
                  data:{
                    electricianCode: this.data.electricianCode
                  },
                  success: (res) => {
                      if(res.data.code == 200){
                        console.log('请求的所有订单状态',res.data.data)
                        this.setData({
                            workOrderStateInfo: res.data.data
                        })

                      }else{
                          wx.showToast({
                            title: res.mesage,
                            icon:'none'
                          });
                      }
                  },
                  fail(){
                    wx.showToast({
                      title: '请求失败',
                      icon:'none'
                    });
                  },
                })
            },
        })
    },

    getfooter: function () {
        var that = this
        wx.getStorage({
            key: 'electricianCode',
            success: (RES) => {
                this.setData({
                    electricianCode: RES.data.electricianCode,
                });
                console.log('electricianCode为', RES.data.electricianCode)
                wx.request({
                    url: api.findUnread,
                    method: 'POST',
                    data: {
                        electricianCode: that.data.electricianCode,
                    },
                    success: function (res) {
                        if (res.data.code == 200) {
                            that.setData({
                                unreadNum: res.data.data.unreadNum,
                            }),
                            console.log("未读消息数量:", that.data.unreadNum)
                            var footerList = {
                                footerTab: 1,
                                footerlist: [{
                                  diy_name: "系统首页",
                                  color: '#221915',
                                  img: "",
                                  selimg: "",
                                  link: "/pages/FirstPage/FirstPage",
                                  unreadNum: that.data.unreadNum,
                                }, {
                                  diy_name: "我的工单",
                                  color: '#221915',
                                  img: "",
                                  selimg: "",
                                  link: "/pages/MyList/MyList"
                                },{
                                  diy_name: "个人中心",
                                  color: '#221915',
                                  img: "",
                                  selimg: "",
                                  link: "/pages/Mine/Mine"
                                }]
                              }
                            that.setData({
                                footer: footerList
                            })
                        }
    
                    }
                })
            },
        });
    
    
    
    },

    // 处理 Picker 选择事件
    onTypeChange(e) {
        const index = e.detail.value;
        const selectedType = this.data.typeOptions[index];
        this.setData({
            selectedType: selectedType,
            workOrderType: selectedType === '派遣' ? 1 : selectedType === '发布' ? 2 : '',
        });
        this.filterWorkOrders(this.data.workOrderType);
    },

    // 根据工单类型，给MyList传不同的数据
    filterWorkOrders(type) {
        console.log(`筛选工单，类型为：${type}`);
        this.setData({
            MyList: this.data.AllList
        })
        const filteredList = this.data.MyList.filter(item => {
            // 根据工单类型进行筛选
            if (type === 1) {
                return item.workOrderType === 1; // 只显示派遣类型工单
            } else if (type === 2) {
                return item.workOrderType === 2; // 只显示发布类型工单
            } else {
                return true; // 显示所有工单
            }
        });

        // 更新显示的工单列表
        this.setData({
            MyList: filteredList
        });
  },    

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('来自onLoad的页面刷新')
        this.getOrderState();
        this.getfooter();
        // 更新页面data
        this.fetchListData();
    },

        fetchListData:function(){
            var that = this;
            wx.getStorage({
                key: 'electricianCode',
                // 根据key成功获取value
                success:(res) => {
                    this.setData({
                        // 设置本页的electricianCode的值
                        electricianCode: res.data.electricianCode
                    });
                
                //  console.log('获取的电工编号为:', this.data.electricianCode);

                // 获取成功后，根据用户的数据，更新工单数据
                wx.request({
                  url: api.findAllByConditionToMe,
                  method: 'POST',
                  data:{
                    workOrderState: -1,
                    electricianCode: this.data.electricianCode,
                    feedbackType: 3,
                    pageNum: that.data.mPageNum,
                    pageSize: "10",
                  },

                  // 成功获取到该电工的数据
                  success: (res) => {
                    wx.hideLoading();
                    if(res.data.code == 200){
                        if(that.data.mPageNum != 1){
                            that.setData({
                                MyList: that.data.MyList.concat(res.data.data.rows)
                            });
                        }else{
                            that.setData({
                                MyList: res.data.data.rows
                            });
                        }
                        console.log('总的返回我的工单数据', res.data.data)
                        console.log('所有工单的详情', res.data.data.rows)
                        // console.log('返回我的工单页testingCode', res.data.data.rows[0].testingCode)
                        // 把后台返回的数据赋值
                        // 把后台接口中rows里面的所有内容当作一个item，把item再作为数组的元素
                        // const MyListData = res.data.data.rows;

 //每个工单都去调一次获取检测结果接口？然后获取testingAgree的值，来改变我的工单界面按钮的显示

                        // 把获取的数据更新到MyList数组中，前端会根据此来进行循环遍历，MyList中存放的是所有的工单
                        // this.setData({
                        //     MyList: MyListData // 数组的值
                        // });

                        this.setData({
                            AllList: this.data.MyList
                        })

                    }else{
                        wx.showToast({
                          title: res.data.mesage,
                          icon: 'none',
                        })
                    }
                  },
                })

                },
                // 获取失败
                fail: function(){
                    wx.showToast({
                      title: '获取失败',
                      icon: 'none'
                    })
                    console.log('打印失败')
                }
            })
        },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.hideHomeButton(); 
        console.log('来自onshow的页面刷新')
        this.getOrderState();
        this.fetchListData();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        var that = this;
        that.setData({
            mPageNum: 1
        });
          this.fetchListData();
          wx.stopPullDownRefresh();
          setTimeout(function() {
            wx.showToast({
                title: '完成刷新',
                icon: 'none'
              });
          }, 1000);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        console.log('触底')
        var that = this;  
        let num = that.data.mPageNum
        that.setData({
            mPageNum: num += 1
        });   
        // 刷新页面订单数据
        this.fetchListData();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
    },

    /**
     * 跳转到场打卡
     */
    toArrive: function(e){
      // 获取点击的订单的信息
      const { item } = e.currentTarget.dataset;
      console.log('item内容', item)

      if(item.workOrderState == 2){
          // 将工单号，电工编号传过去
        wx.navigateTo({
            url: `/pages/MyList/Card/Card?workOrderCode=${item.workOrderCode}&electricianCode=${item.electricianCode}`
          });
      }else{    
          // 根据当前订单的状态，跳转到相同的页面，区别在于底部的按钮
        if(item.workOrderState == 3 || item.workOrderState == 4){
            wx.navigateTo({
                url: `/pages/MyList/Detail_checkResult/Detail_checkResult?workOrderCode=${item.workOrderCode}`
              });   
        }else{
            if(item.workOrderState == 5){
                wx.navigateTo({
                    url: `/pages/MyList/Detail_checkResult/Detail_checkResult?workOrderCode=${item.workOrderCode}`
                  });  
            }else{
                if(item.workOrderState == 6){
                    wx.navigateTo({
                        url: `/pages/MyList/Detail_checkResult/Detail_checkResult?workOrderCode=${item.workOrderCode}`
                      });
                }
            }
        }
      }
    },
})